package com.example.merchantdemo.paymentstart.controller;

import com.example.merchantdemo.paymentstart.dto.PlatformResponse;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * controller层全局异常处理，确保不返回异常及堆栈信息
 *
 * @Author
 */
@RestControllerAdvice
public class ControllerExceptionHandler {

    /**
     * 处理 Bean validator 返回的信息
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object methodArgumentNotValidHandler(MethodArgumentNotValidException exception) {
        PlatformResponse platformResponse = new PlatformResponse();
        //解析原错误信息，封装后返回，此处返回非法的字段名称，错误信息
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            platformResponse.setCode(9999);
            platformResponse.setMessage(error.getDefaultMessage());
        }
        return platformResponse;
    }

    @ExceptionHandler(Exception.class)
    public PlatformResponse exceptionHandler(Exception e) {
        PlatformResponse platformResponse = new PlatformResponse();
        platformResponse.setCode(9999);
        platformResponse.setMessage(e.getMessage());
        e.printStackTrace();
        return platformResponse;
    }
}
